import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Space,
  Upload,
} from 'antd';
import { Link } from 'react-router-dom';
import Cannels from 'components/Cannels';
// 富文本
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';
import { baseURL } from 'utils/request';
import { gettoken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';
import {
  addArticlelistAPI,
  getArticlebyidAPI,
  setArticlebyidAPI,
} from 'api/article';

export default function ArticlePublish(_props) {
  // 1. 声明状态控制Upload的fileList ，等价于表单的value
  const [fileList, setFileList] = useState([]);
  const [imgSrc, setImgSrc] = useState('');
  // 1. 声明type的state
  const [type, setType] = useState(1);

  // 0. 接口提前改造
  // 1. 声明ref，保存draft的标识
  const draftRef = useRef(false);
  const formRef = useRef({});

  // 3. 事件冒泡到onFinish时，请求参数中带上ref
  // 1. 提取了配置props
  const props = {
    // 1.1 name代表后台支持上传文件的类型，值由后台决定
    name: 'image',
    // 文件上传框，默认支持的文件类型
    accept: '.png,.jpg,.jpeg',
    // 1.2 代表上传文件的请求url地址
    action: `${baseURL}/v1_0/upload`,
    // 1.3 加上token
    headers: {
      authorization: `Bearer ${gettoken()}`,
    },
    // 2. onChange事件改变fileList
    onChange(info) {
      // console.log('info  ----->  ', info);
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    onPreview(file) {
      setImgSrc(file.thumbUrl);
    },
    // 配置beforeUpload钩子函数
    beforeUpload(file) {
      const imgs = ['image/jpg', 'image/png', 'image/jpeg'];
      if (!imgs.includes(file.type)) {
        message.warning('不允许上传的文件类型', 1);
        return Upload.LIST_IGNORE;
      }
    },
  };
  // 2. 绑定onValuesChange事件，任意值改变事件
  const handleValuesChange = (changedValues, allValue) => {
    // 2.1 判断changedValues有type这个属性，且不为undefined的时候，setState更新type
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };
  // 控制图片数量
  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });

  const handleFinish = async (values) => {
    // 1. 加判断条件 -数量不对,提示用户阻止执行
    if (showFileList.length !== type) {
      return message.warning('图片数量不正确', 1);
    }

    // console.log(values);
    let formData = { ...values };

    formData.cover = {
      type: values.type,
      // 2. 以用户界面上看到的为准，发给后台
      images: showFileList.map((item) =>
        item.response ? item.response.data.url : item.url
      ),
    };
    delete formData.type;
    console.log(formData);
    if (articleId) {
      await setArticlebyidAPI(articleId, formData, draftRef.current);
      message.success('编辑成功', 1);
    } else {
      await addArticlelistAPI(formData, draftRef.current);
      message.success('发布成功', 1);
    }
    _props.history.push('/list');
  };
  // 3. 获取传来id
  const articleId = _props.match.params.id;
  const loadArticleById = async (id) => {
    const res = await getArticlebyidAPI(id);
    console.log(res.data);
    formRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });
    setType(res.data.cover.type);
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  };
  useEffect(() => {
    if (articleId) {
      loadArticleById(articleId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <div
      style={{ padding: 24, height: 'calc(100vh - 64px)', overflow: 'auto' }}
      className={styles.root}
    >
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {`${articleId ? '编辑' : '发布'}`}文章
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 24 }}
          autoComplete="off"
          onFinish={handleFinish}
          // 💥注意，给组件加上初始值和name
          initialValues={{
            content: '',
            type: 1,
          }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '标题不能为空' }]}
          >
            <Input size="large" placeholder="请输入文章标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请输入文章频道' }]}
          >
            <Cannels></Cannels>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true },
              {
                message: '请输入文章内容',
                validator: (_, value) => {
                  // 判断value的值为   返回失败的信息
                  // 1. 判断是否为空标签
                  // 2.使用自定义校验，返回  Promise.resolve() 代表通过。 Promise.reject()代表失败
                  if (value === '<p><br></p>' || !value) {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 3. 使用FormItem 并且设置偏移量 */}
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={showFileList}>
              {/* 4. 使用表达式控制按钮的显示与否 */}
              {fileList.length < type && <UploadOutlined />}
            </Upload>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {`${articleId ? '编辑' : '发布'}`}文章
              </Button>
              <Button
                type="dashed"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      {/* 4. 设置Modal组件的位置 */}
      <Modal
        maskClosable={false}
        title="预览图片"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img width={480} style={{ objectFit: 'cover' }} src={imgSrc} alt="" />
      </Modal>
    </div>
  );
}
